#pragma once

#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock,InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,ioservice_t service)
        : _port(port),
          _listensocketptr(std::make_unique<TcpSocket>()),
          _isruning(false),
          _service(service)
    {
        _listensocketptr->BuildTcpSocketMethod(_port);
    }
    void Start()
    {
        _isruning = true;
        while (_isruning)
        {
            InetAddr client;
            auto sock = _listensocketptr->Accept(&client);
            if(sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "access success..." << client.StringAddr();
            pid_t id = fork();
            if(id<0)
            {
                LOG(LogLevel::FATAL) << "fork error...";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                //子进程
                _listensocketptr->Close();//不需要之前的套接字，关闭
                if(fork()>0)
                    exit(OK);
                //到这里是孙子进程执行任务，已经是孤儿了
                _service(sock,client);
                sock->Close();
                exit(OK);
            }
            else
            {
                //父进程关闭
                sock->Close();//这里就是返回Tcpserver的好处了，也可以用Close函数
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }
        }
        _isruning = false;
    }
    ~TcpServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocketptr;
    bool _isruning;
    ioservice_t _service;
};